package cn.gary.oaserver.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.gary.oaserver.config.utils.PageUtil;
import cn.gary.oaserver.entity.*;
import cn.gary.oaserver.params.Result;
import cn.gary.oaserver.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author gary
 * @since 2024-03-15
 */
@RestController
@RequestMapping("/employee")
public class TEmployeeController {

    @Autowired
    ITEmployeeService employeeService;

    @Autowired
    ITDepartmentService departmentService;

    @Autowired
    ITPoliticsStatusService politicsStatusService;

    @Autowired
    ITNationService nationService;

    @Autowired
    ITJoblevelService joblevelService;

    @Autowired
    ITPositionService positionService;


    @ApiOperation("条件查询所有员工")
    @GetMapping("/basic/list")
    public Result getEmpByQuery(@RequestParam(value = "empName", required = false) String empName,
                                @RequestParam(value = "politicsId", defaultValue = "0", required = false) Integer politicsId,
                                @RequestParam(value = "deptId", defaultValue = "0", required = false) Integer deptId,
                                @RequestParam(value = "beginTime", required = false) String beginTime,
                                @RequestParam(value = "endTime", required = false) String endTime,
                                @RequestParam(value = "sort", defaultValue = "+id", required = false) String sort,
                                @RequestParam(value = "pageSize", defaultValue = "5", required = false) Integer pageSize,
                                @RequestParam(value = "currPageNo", defaultValue = "1", required = false) Integer currPageNo) {
        Page<TEmployee> pageInfo = new Page<> ( currPageNo, pageSize );
        IPage<TEmployee> pages = employeeService.getEmpByQuery ( pageInfo, empName, politicsId, deptId, beginTime, endTime, sort );

        Map<String, Object> map = new HashMap<> ( );
        PageUtil<TEmployee> page = new PageUtil<>
                ( Math.toIntExact ( pages.getCurrent ( ) ),
                        Math.toIntExact ( pages.getTotal ( ) ),
                        pages.getRecords ( ) );
        map.put ( "pages", page );
        map.put ( "politcList", politicsStatusService.list ( ) );
        map.put ( "deptList", departmentService.getAllDepartments ( ) );
        return Result.success ( "获取员工列表", map );
    }

    @ApiOperation("导出员工资料")
    @GetMapping("/basic/exportData")
    @PreAuthorize("hasAuthority('/employee/basic/exportData')")
    public void empExportExcel(HttpServletResponse response, @RequestParam(value = "empName", required = false) String empName,
                               @RequestParam(value = "politicsId", defaultValue = "0", required = false) Integer politicsId,
                               @RequestParam(value = "deptId", defaultValue = "0", required = false) Integer deptId,
                               @RequestParam(value = "beginTime", required = false) String beginTime,
                               @RequestParam(value = "endTime", required = false) String endTime,
                               @RequestParam(value = "sort", defaultValue = "+id", required = false) String sort,
                               @RequestParam(value = "pageSize", defaultValue = "5", required = false) Integer pageSize,
                               @RequestParam(value = "currPageNo", defaultValue = "1", required = false) Integer currPageNo) {
        Page<TEmployee> pageInfo = new Page<> ( currPageNo, pageSize );
        IPage<TEmployee> pages = employeeService.getEmpByQuery ( pageInfo, empName, politicsId, deptId, beginTime, endTime, sort );
        List<TEmployee> empRecords = pages.getRecords ( );
        System.out.println ( pages.getRecords ( ) );

        String title = "员工表_" + System.currentTimeMillis ( );
        ExportParams exportEmp = new ExportParams ( title, "员工表", ExcelType.HSSF );
        Workbook workbook = ExcelExportUtil.exportExcel ( exportEmp, TEmployee.class, empRecords );
        ServletOutputStream out = null;
        try {
            //输出流格式
            response.setHeader ( "content-type", "application/octet-stream" );
            //防止中文乱码
            response.setHeader ( "content-disposition", "attachment;filename=" + URLEncoder.encode ( title + ".xls", "UTF-8" ) );
            out = response.getOutputStream ( );
            workbook.write ( out );
        } catch (IOException e) {
            e.printStackTrace ( );
        } finally {
            if (out != null) {
                try {
                    out.close ( );
                } catch (IOException e) {
                    e.printStackTrace ( );
                }
            }
        }

    }

    @ApiOperation("导入员工资料")
    @PostMapping(value = "/basic/importData")
    @PreAuthorize("hasAuthority('/employee/basic/importData')")
    public Result empImportExcel(MultipartFile file) {
        ImportParams params = new ImportParams ( );
        params.setTitleRows ( 1 );
        try {
            List<TEmployee> list = ExcelImportUtil.importExcel ( file.getInputStream ( ), TEmployee.class, params );
            System.out.println ( list );
            list.stream ( ).map ( emp -> {
                List<TDepartment> departments = departmentService.list ( new QueryWrapper<TDepartment> ( ).eq ( "name", emp.getDepartment ( ).getName ( ) ) );
                if (!CollectionUtils.isEmpty ( departments )) {
                    emp.setDepartmentId ( departments.get ( 0 ).getId ( ) );
                }
                List<TPoliticsStatus> politicsStatus = politicsStatusService.list ( new QueryWrapper<TPoliticsStatus> ( ).eq ( "name", emp.getPoliticsStatus ( ).getName ( ) ) );
                if (!CollectionUtils.isEmpty ( politicsStatus )) {
                    emp.setPosId ( politicsStatus.get ( 0 ).getId ( ) );
                }
                List<TNation> nations = nationService.list ( new QueryWrapper<TNation> ( ).eq ( "name", emp.getNation ( ).getName ( ) ) );
                if (!CollectionUtils.isEmpty ( nations )) {
                    emp.setNationId ( nations.get ( 0 ).getId ( ) );
                }
                List<TJoblevel> joblevels = joblevelService.list ( new QueryWrapper<TJoblevel> ( ).eq ( "name", emp.getJoblevel ( ).getName ( ) ) );
                if (!CollectionUtils.isEmpty ( joblevels )) {
                    emp.setJobLevelId ( joblevels.get ( 0 ).getId ( ) );
                }
                List<TPosition> positions = positionService.list ( new QueryWrapper<TPosition> ( ).eq ( "name", emp.getPosition ( ).getName ( ) ) );
                if (!CollectionUtils.isEmpty ( positions )) {
                    emp.setPoliticId ( positions.get ( 0 ).getId ( ) );
                }
                return emp;
            } ).collect ( Collectors.toList ( ) );
            if (employeeService.saveBatch ( list )) {
                return Result.success ( "导入成功!" );
            }
        } catch (Exception exception) {
            exception.printStackTrace ( );
        }
        return Result.error ( "导入失败" );
    }

    // 获取工号，原理是取t_employee表中workId列的最大值再+1
    @ApiOperation("获取工号")
    @GetMapping("/basic/maxWorkID")
    public Result maxWorkID() {
        return employeeService.maxWorkID();
    }

    @PreAuthorize("hasAuthority('/employee/basic/saveBasic')")
    @ApiOperation("新增员工基本资料")
    @PostMapping("/basic/saveBasic")
    public Result addEmp(@RequestBody TEmployee employee) {
        return employeeService.insertEmp (employee);
    }

    @PreAuthorize("hasAuthority('/employee/basic/updateBasic')")
    @ApiOperation("修改员工基本资料")
    @PostMapping("/basic/updateBasic")  
    public Result updateEmp(@RequestBody TEmployee employee) {
        return employeeService.updateEmp (employee);
    }

    @PreAuthorize("hasAuthority('/employee/basic/delBasic')")
    @ApiOperation("删除员工基本资料")
    @DeleteMapping("/basic/delBasic/{id}")
    public Result delEmp(@PathVariable("id") Integer id){
        return employeeService.delEmp(id);
    }

    @ApiOperation("根据员工id获取员工基本资料")
    @GetMapping("/basic/delBasic/findById/{id}")
    public TEmployee findById(@PathVariable("id") Integer id){
        return employeeService.getById (id);
    }


    @ApiOperation("查询t_department部门表带层级关系的部门列表信息")
    @GetMapping("/basic/treeDeptList")
    public List<TDepartment> treeDeptList() {
        return departmentService.getAllDepartments();
    }

    @ApiOperation("查询t_position职位列表信息")
    @GetMapping("/basic/getPosition")
    public List<TPosition> getPosition() {
        return positionService.list ();
    }

    @ApiOperation("查询t_nation民族列表信息")
    @GetMapping("/basic/getNation")
    public List<TNation> getNation() {
        return nationService.list ();
    }

    @ApiOperation("查询t_joblevel职称名称列表信息")
    @GetMapping("/basic/getJoblevel")
    public List<TJoblevel> getJoblevel() {
        return joblevelService.list ();
    }

    @ApiOperation("查询t_getPoliticsStatus政治面貌列表信息")
    @GetMapping("/basic/getPoliticsStatus")
    public List<TPoliticsStatus> getTPoliticsStatus() {
        return politicsStatusService.list ();
    }
}
